#!/bin/bash
# 审计日志删除与备份压缩
# 30 4 * * * source $HOME/.bash_profile && sh /sumz/script/mysql_general_bak.sh >> /sumz/mysql_general_bak.log 2>&1
# 定义备份目录
bakurl="/sumz/data_bak/mysql_general_bak_file"

# 备份MySQL日志函数
backup_mysql_log() {
    /usr/local/bin/kubectl exec mysql-0 -n base -ti -- sh -c 'cp /var/lib/mysql/mysql-0.log /var/lib/mysql/mysql-bak.log ; cp /dev/null /var/lib/mysql/mysql-0.log'
    /usr/local/bin/kubectl cp mysql-0:/var/lib/mysql/mysql-bak.log "$bakurl/mysql-bak.log" -n base
}

# 打包备份文件函数
pack_backup_files() {
    cd "$bakurl"
    tar -czvf "$(date +'%Y%m%d-%H%M%S').tar.gz" mysql-bak.log
    rm -f "$bakurl/mysql-bak.log"
}

# 删除一个月以前的文件（除星期五以外）
delete_old_files() {
    cd "$bakurl"
    rtime=$(date -d "$(date +%Y-%m-%d -d '-30 day')" +%s)
    for filename in $(ls "$bakurl")
    do
        fntime=$(date -d $(ls --full-time $filename | awk {'print $6'}) +%w)
        baktime=$(date -d $(ls --full-time $filename | awk {'print $6'}) +%s)
        if [ $rtime -gt $baktime ] && [ $fntime -ne 5 ]
        then
            rm -f "$bakurl/$filename"
        fi
    done
}

# 备份MySQL日志并打包文件
backup_mysql_log
pack_backup_files
# 清理旧文件
delete_old_files
